package com.zy.fee.roadpark.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.inputmethodservice.Keyboard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.activity.np.LeaveNotPicActivity;
import com.zy.fee.roadpark.adapter.LeaveApplyNotAdapter;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.model.M_NpNodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_NpNodeRecordList;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseFragment;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.JsonUtil;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.SmoothListView.SmoothListView;
import com.zygk.library.view.XKeyboardView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class LeaveApplyNotFragment extends BaseFragment
    implements SmoothListView.ISmoothListViewListener {

  public static final String TAG = LeaveApplyNotFragment.class.getSimpleName();

  @BindView(R.id.smoothListView) SmoothListView mSmoothListView;
  @BindView(R.id.tv_apply_date) TextView tvApplyDate;
  @BindView(R.id.rl_no_data) RelativeLayout rlNoData;
  @BindView(R.id.iv_delete_date) ImageView ivDeleteDate;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.view_keyboard) XKeyboardView viewKeyboard;

  Context mContext;
  Activity mActivity;
  Unbinder unbinder;
  int page = 1;
  private String handleDate = "", carNumber = "";
  private List<M_NpNodeRecord> nodeRecordList = new ArrayList<>();
  private LeaveApplyNotAdapter leaveApplyNotAdapter;
  private TimePickerView pvTime;
  private String applyDate;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_leave_apply_not, null);
    unbinder = ButterKnife.bind(this, v);
    return v;
  }

  @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    init();
  }

  /**
   * 初始化
   */
  private void init() {
    initData();
    initView();
    initListener();
    getNetWorkInfo();
  }

  @Override public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
      if (nodeRecordList.size() < 1) getNetWorkInfo();
    }
  }

  @Override public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if (!hidden) {
      getNetWorkInfo();
    } else {
    }
  }

  private void getNetWorkInfo() {
    showPd();
    getDataList(false);
  }

  private void getDataList(boolean isLoadMore) {
    NpNodeRecordLogic.npnode_record_apply_list(mContext, 0, carNumber, handleDate,
        isLoadMore ? ++page : (page = 1),
        Constants.ROWS, new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NpNodeRecordList result = (APIM_NpNodeRecordList) obj;
            nodeRecordList = result.getNpnodeRecordList();
            System.out.printf(JsonUtil.objectToJson(nodeRecordList));
            fillAdapter(result.getNpnodeRecordList(), result.getMaxpage(), isLoadMore);
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            mSmoothListView.stopRefresh();
            mSmoothListView.stopLoadMore();
            dismissPd();
          }
        });
  }

  private void fillAdapter(List<M_NpNodeRecord> list, int maxPage, boolean isLoadMore) {
    if (list == null || list.size() == 0) {
      rlNoData.setVisibility(View.VISIBLE);
      mSmoothListView.setVisibility(View.GONE);
      mSmoothListView.setLoadMoreEnable(false);
    } else {
      rlNoData.setVisibility(View.GONE);
      mSmoothListView.setVisibility(View.VISIBLE);
      mSmoothListView.setLoadMoreEnable(page < maxPage);
      leaveApplyNotAdapter.setData(list, isLoadMore);
    }
  }

  private void initData() {
    mContext = getActivity();
    mActivity = getActivity();
    registerReceiver(new String[] {
        Constants.BROADCAST_REFRESH_NODE_RECORD_LIST
    });
    leaveApplyNotAdapter = new LeaveApplyNotAdapter(mContext, nodeRecordList);
    mSmoothListView.setAdapter(leaveApplyNotAdapter);
    gpvPlateNumber.setPassword("苏");

  }

  private void initView() {
    mSmoothListView.setSmoothListViewListener(this);
    mSmoothListView.setRefreshEnable(true);
    mSmoothListView.setLoadMoreEnable(false);
  }

  private void initListener() {
    viewKeyboard.setIOnKeyboardListener(new XKeyboardView.IOnKeyboardListener() {
      @Override public void onInsertKeyEvent(String text) {
        gpvPlateNumber.appendPassword(text);
      }

      @Override public void onDeleteKeyEvent() {
        gpvPlateNumber.deletePassword();
      }
    });

    gpvPlateNumber.togglePasswordVisibility();

    gpvPlateNumber.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
      @Override public boolean beforeInput(int position) {
        if (position == 0) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.provice));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 1 && position < 2) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.english));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        } else if (position >= 2 && position <= 7) {
          viewKeyboard.setKeyboard(new Keyboard(mContext, R.xml.qwerty_without_chinese));
          viewKeyboard.setVisibility(View.VISIBLE);
          return true;
        }
        viewKeyboard.setVisibility(View.GONE);
        return false;
      }

      @Override public void onTextChanged(String psw) {
      }

      @Override public void onInputFinish(String psw) {
      }
    });

    gpvPlateNumber.setOnFocusChangeListener((v, hasFocus) -> {
      if (!hasFocus) {
        viewKeyboard.setVisibility(View.GONE);
      }
    });

    leaveApplyNotAdapter.setItemDeleteClickListener(
        (m, position) -> {
          CommonDialog.showYesOrNoDialog(mContext, "驶离申请处理", "未驶离", "已驶离", () -> {
            //已驶离
            showLeaveDialog(m);
          }, () -> {
            Intent i = new Intent(mContext, LeaveNotPicActivity.class);
            i.putExtra("NodeRecord", m);
            startActivity(i);
          });
        });
  }

  //处理结果(0:未驶离,取证,1:已驶离)
  private void showLeaveDialog(M_NpNodeRecord m) {
    CommonDialog.showYesOrNoWithTitleDialog(mContext, "", "确认车辆" + m.getCarNumber() + "已经驶离了吗?",
        "取消",
        "确认", () -> {
          applyHandle(m.getNodeRecordID(), 1, "");
        }, () -> {
        });
  }

  private void applyHandle(String nodeRecordID, int state, String pic) {
    NpNodeRecordLogic.npnode_record_apply_handle(mContext, nodeRecordID, state, pic,
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            ToastUtil.showMessage(mContext, "处理成功");
            mContext.sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_RECORD_LIST));
            getDataList(false);
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  //选择日期
  private void showDatePicker() {
    Date now = new Date();
    Calendar selectedDate = Calendar.getInstance();
    Calendar sDate = Calendar.getInstance();
    sDate.set(now.getYear() + 1900 - 1, now.getMonth() - 1, now.getDate());
    Calendar eDate = Calendar.getInstance();
    eDate.set(now.getYear() + 1900, now.getMonth(), now.getDate());
    pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
      @Override public void onTimeSelect(Date date, View v) {//选中事件回调
        applyDate = DateTimeUtil.getFormatDate(date);
        tvApplyDate.setText(applyDate);
        ivDeleteDate.setVisibility(View.VISIBLE);
      }
    }).setType(new boolean[] { true, true, true, false, false, false })//默认全部显示
        .setCancelText("取消")//取消按钮文字
        .setSubmitText("确定")//确认按钮文字
        .setContentTextSize(18)//滚轮文字大小
        .setTitleSize(20)//标题文字大小
        .setTitleText("选择开始日期")//标题文字
        .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
        .isCyclic(false)//是否循环滚动
        .setTitleColor(Color.BLACK)//标题文字颜色
        .setSubmitColor(getResources().getColor(R.color.theme_color))//确定按钮文字颜色
        .setCancelColor(Color.BLACK)//取消按钮文字颜色
        .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
        .setBgColor(Color.WHITE)//滚轮背景颜色 Night mode
        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
        .setRangDate(sDate, eDate)//起始终止年月日设定
        .isDialog(false)//是否显示为对话框样式
        .build();
    pvTime.show();
  }

  @Override public void onRefresh() {
    getDataList(false);
  }

  @Override public void onLoadMore() {
    getDataList(true);
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_REFRESH_NODE_RECORD_LIST.equals(intent.getAction())) {
      onRefresh();
    }
  }

  @OnClick({
      R.id.tv_button, R.id.tv_apply_date, R.id.iv_delete_date,
  })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.tv_button:
        viewKeyboard.setVisibility(View.GONE);
        handleDate = tvApplyDate.getText().toString();
        carNumber = gpvPlateNumber.getPassWord();
        getDataList(false);
        break;
      case R.id.tv_apply_date:
        viewKeyboard.setVisibility(View.GONE);
        showDatePicker();
        break;
      case R.id.iv_delete_date:
        tvApplyDate.setText("");
        ivDeleteDate.setVisibility(View.GONE);
        break;
    }
  }
}
